# -*- codeing = utf-8 -*-
# @Time  :2021/6/30 10:01
# @Author:汪煜晗
# @File  :DataVis.py
# @Software: PyCharm
import numpy as np
import pandas as pd
import wordcloud
import stylecloud
from collections import Counter
import matplotlib.pyplot as plt


def DataProcess(path='./BaiduScholar/BaiduScholar.xlsx'):
    '''
    提取时间信息和关键词，返回时间信息格式为np.array，关键词信息格式为list
    '''
    # 读取数据
    read_data = pd.read_excel(path)
    keyword = []
    for item in read_data['keyword']:   # 读取关键词信息
        k = str(item)
        # 规范关键词格式
        k = k.replace('[', '')
        k = k.replace(']', '')
        k = k.replace('\'', '')
        k = k.replace('；', '、') if '；' in k else k.replace(',', '、') if ',' in k else k
        k = k.split('、')
        if k[-1] == '':
            del k[-1]
        keyword.append(k)
    # 规范时间信息
    t = read_data['time']  # 读取时间信息
    t = t.dropna(axis=0, how='all')  # 清除Nan
    time = np.asarray(t)
    return keyword, time

def cloud_show(KW, save_path='./BaiduScholar/stylecloud.png'):
    result = {}
    for item in KW:
        for words in item:
            word = words.strip()
            print(word)
            if len(word) == 1:    # 单个字不记录
                continue
            else:
                result[word] = result.get(word, '') + ' ' + word   # 重复的词语累加统计量
        result_text = " ".join(result.values())     # 获取全部词汇

        stylecloud.gen_stylecloud(text=result_text, collocations=False,
                                  font_path=r'C:\Windows\Fonts\STXINGKA.TTF',
                                  icon_name='fas fa-dog',
                                  size=600,
                                  output_name=save_path
                                  )
        # cloud = wordcloud.WordCloud(
        #     # 设置字体路径、背景色、宽度、高度
        #     font_path=r'C:\Windows\Fonts\STXINGKA.TTF',
        #     background_color='white', width=1000, height=380
        # )
        # cloud.generate(result_text)    # 加载处理文本
        # cloud.to_file(save_path)                # 保存处理结果

def time_show(TM, save_path='./BaiduScholar/time.png'):
    # 统计个时间文章数量
    num = pd.DataFrame([Counter(TM)])  # 将统计结果的字典类型转换为DataFrame
    num.sort_index(axis=1, ascending=True, inplace=True)      # 对列索引进行升序
    # 可视化
    fig, ax = plt.subplots()
    # ggplot (a popular plotting package for R).
    plt.style.use('ggplot')
    TimeLabel = num.columns.values.tolist()
    TimeLabel = list(map(int, TimeLabel))
    y_num = np.arange(len(TimeLabel))
    timedata = num.iloc[0,:].values
    p1 = ax.barh(y_num, timedata, align='center', color=list(plt.rcParams['axes.prop_cycle'])[2]['color'])
    ax.set_yticks(y_num)
    ax.set_yticklabels(TimeLabel)
    ax.invert_yaxis()  # labels read top-to-bottom
    # 增加标签
    # ax.bar_label(p1, padding=3)
    ax.set_xlabel('number')
    ax.set_title('The number of articles')
    plt.savefig(save_path, dpi=800)
    plt.show()


def main():
    Keyword, time = DataProcess()
    cloud_show(KW=Keyword)
    time_show(TM=time)
